package cn.lvhang.user.controller;

import cn.lvhang.basic.exception.BusinessException;
import cn.lvhang.basic.util.AjaxResult;
import cn.lvhang.basic.util.PageList;
import cn.lvhang.user.domain.User;
import cn.lvhang.user.dto.UserDto;
import cn.lvhang.user.query.UserQuery;
import cn.lvhang.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController // @Controller +@ResponseBody
@RequestMapping("/user")
@Api(tags = "用户接口",description = "用户接口详细描述")//用于对swagger字段的描述
public class UserController {
    @Autowired
    private IUserService userService;
    //新增或修改
    @PutMapping
    @ApiOperation(value = "用户添加或修改",notes = "如果有id就是修改否则就是添加")//用于对swagger字段的描述
    public AjaxResult addOrUpdate(@RequestBody User user){
        try {
            if(user.getId() == null){
                userService.add(user);
            }else{
                userService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！");
        }

    }
    //删除
    @DeleteMapping("/{id}")
    public AjaxResult deleteById(@PathVariable("id") Long id){
        try {
            userService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！");
        }
    }
    //查询单个
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id){
        return userService.queryById(id);
    }
    //查询所有
    @GetMapping
    public List<User> queryAll(){
        return userService.queryAll();
    }

    //分页 + 高级查询
    // @RequestBody接收前台发送的json字符串
    @PostMapping
    public PageList<User> queryPage(@RequestBody UserQuery query){
        return userService.queryPage(query);
    }
    //批量删除
    @PatchMapping
    public AjaxResult patchDelete(@RequestBody List<Long> ids){
        try {
            userService.patchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("操作失败！");
        }
    }
    @PostMapping("/phone/register")
    public AjaxResult register(@RequestBody UserDto userDto) {
        try {
            userService.register(userDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me()
                    .setMessage("系统繁忙！请稍后重试！");
        }

    }
}
